package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.utils.BeanUtil;
import com.cpit.platform.dto.User;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.qualitycontrol.dao.ProductLineRepository;
import com.cpit.qualitycontrol.dao.ProjectRepository;
import com.cpit.qualitycontrol.dao.UserToProductLineRepository;
import com.cpit.qualitycontrol.entity.ProductLine;
import com.cpit.qualitycontrol.entity.UserToProductLine;
import com.cpit.qualitycontrol.service.ProductLineService;
import com.cpit.qualitycontrol.service.UserToProductLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hull on 2017/9/28.
 *
 * @author Hull
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProductLineServiceImpl implements ProductLineService {
    private final String loggerName = this.getClass().getName();

    @Autowired
    private ProductLineRepository rep = null;

    @Autowired
    private ProjectRepository projectRepository = null;

    @Autowired
    private UserToProductLineService userToProductLineService;

    @Autowired
    private UserToProductLineRepository userToProductLineRepository;

    @Override
    public ProductLine findById(Long id) {
        return this.rep.findOne(id);
    }

    @Override
    public List<ProductLine> findAll() {
        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            Long productLineId = new Long((long) list.get(0).getProductLineId());
            ProductLine productLine = findById(productLineId);
            List<ProductLine> ret = new ArrayList<ProductLine>();
            ret.add(productLine);
            return ret;
        }

        return this.rep.findAll();
    }

    @Override
    public List<ProductLine> findByCondition(int page, int size, String order, String orderBy, String pattern) {
        if (orderBy == null || orderBy.length() == 0) {
            orderBy = "id";
        }
        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
        Page<ProductLine> pg;
        if (pattern == null || "".equals(pattern)) {
            pg = this.rep.findAll(request);
        } else {
            pg = this.rep.findByNameContaining(pattern, request);
        }
        return pg.getContent();
    }

    @Override
    public ProductLine create(ProductLine productLine) throws Exception {
        if (productLine == null) {
            throw new Exception("参数为空");
        }
        if (productLine.getId() != null && productLine.getId() > 0) {
            LogOperator.info(loggerName, "产品线ID已赋值");
            productLine.setId(0L);
        }
        this.checkUniqueConstraint(productLine);

        return this.rep.save(productLine);
    }

    @Override
    public ProductLine modify(ProductLine productLine) throws Exception {
        if (productLine == null) {
            throw new Exception("参数为空");
        }

        ProductLine dt = rep.findOne(productLine.getId());
        if (dt == null) {
            LogOperator.info(loggerName, "修改的产品线不存在:" + productLine);
            throw new Exception("修改的产品线不存在");
        }
        this.checkUniqueConstraint(productLine);

        return this.rep.save(productLine);
    }

    @Override
    public void delete(ProductLine productLine) throws Exception {
        if (productLine == null) {
            throw new Exception("参数为空");
        }
        this.delete(productLine.getId());
    }

    @Override
    public void delete(Long id) throws Exception {
        ProductLine dt = rep.findOne(id);
        if (dt == null) {
            LogOperator.info(loggerName, "删除的产品线不存在:id=" + id);
            throw new Exception("删除的产品线不存在");
        }

        List<UserToProductLine> up = userToProductLineRepository.findByProductLineId(id.intValue());
        if (up != null && up.size() > 0) {
            LogOperator.info(loggerName, "该产品线下存在用户信息，不能删除产品线:" + id);
            throw new Exception("该产品线下存在用户信息，不能删除产品线");
        }

        if (this.projectRepository.countAllByProductLineId(id) > 0) {
            LogOperator.info(loggerName, "该产品线下存在项目信息，不能删除产品线:" + id);
            throw new Exception("该产品线下存在项目信息，不能删除产品线");
        }

        this.rep.delete(id);
    }

    @Override
    public TableJsonData findByConditionJqg(TableDataQueryCondition cond) {
        PageRequest request = ServiceUtils.getPageRequestByTableDataQueryCondition(cond);

        String pattern = BeanUtil.getStringIdentifyNull(cond.getQueryCond().get("pattern"));
        Page<ProductLine> ret;
        if (pattern == null || "".equals(pattern)) {
            ret = this.rep.findAll(request);
        } else {
            ret = this.rep.findByNameContaining(pattern, request);
        }
        return new TableJsonData(cond, ret.getTotalElements(), ret.getContent());
    }

    private void checkUniqueConstraint(ProductLine productLine) throws Exception {
        ProductLine productLine1 = rep.findByName(productLine.getName());
        if (productLine1 != null && !productLine1.getId().equals(productLine.getId())) {
            LogOperator.info(loggerName, "同名产品线已存在:" + productLine.getName());
            throw new Exception("同名产品线已存在");
        }
    }

    /**
     * 获取登录用户信息
     *
     * @return
     */
    private User getLoginUser() {
        return ((UserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal()).getUser();
    }
}
